package com.lnlyj.media.ui;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;

import com.lnlyj.media.Config;
import com.lnlyj.media.LnlyjSelector;
import com.lnlyj.media.R;
import com.lnlyj.media.base.BaseActivity;
import com.lnlyj.media.util.PermissionUtils;

import java.util.List;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;

import static com.lnlyj.media.Constants.EXTRA_CONFIG;
import static com.lnlyj.media.Constants.REQUEST_CODE_MEDIA;

/**
 * wanglei 2020-04-16
 */
public class MediaActivity extends BaseActivity implements PermissionUtils.PermissionListener {

    private Config config;

    public static void call(Activity activity, Config config) {
        Intent intent = new Intent(activity, MediaActivity.class);
        intent.putExtra(EXTRA_CONFIG, config);
        activity.startActivityForResult(intent, REQUEST_CODE_MEDIA);
    }

    public static void call(Fragment fragment, Config config) {
        Intent intent = new Intent(fragment.getActivity(), MediaActivity.class);
        intent.putExtra(EXTRA_CONFIG, config);
        fragment.startActivityForResult(intent, REQUEST_CODE_MEDIA);
    }

    private MediaFragment fragment;


    public MediaActivity() {
        super(R.layout.activity_media);
    }

    @Override
    public void initView() {
        config = getIntent().getParcelableExtra(EXTRA_CONFIG);
        if (config == null) {
            config = LnlyjSelector.getInstance().getGlobalConfig();
        }
    }

    @Override
    public void initData() {
        PermissionUtils.requestPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE, this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        SelectionManager.getInstance().clear();
    }

    private void initFragment() {
        FragmentManager fm = getSupportFragmentManager();

        fragment = (MediaFragment) fm.findFragmentByTag(MediaFragment.TAG);

        if (fragment != null) {
            fm.beginTransaction().remove(fragment).commit();
        }
        fragment = MediaFragment.getInstance(false, config);
        fm.beginTransaction().add(R.id.layout_content, fragment, MediaFragment.TAG).show(fragment).commit();
    }

    @Override
    public void onShouldShowRequestPermissions(List<String> permissions) {

    }

    @Override
    public void onGranted() {
        initFragment();
    }

    @Override
    public void onGranted(List<String> grantedPermission) {

    }

    @Override
    public void onDenied(List<String> deniedPermission) {
        finish();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionUtils.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }
}
